/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package putime.newspaperagent.line;

import java.awt.Color;
import java.awt.event.ItemEvent;
import java.text.DateFormat;
import java.sql.Date;
import java.text.SimpleDateFormat;
import java.util.Vector;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
import javax.swing.ComboBoxModel;
import javax.swing.DefaultComboBoxModel;
import javax.swing.DefaultListModel;
import javax.swing.JOptionPane;
import putime.model.ModelLine;
import putime.model.ModelSupplier;
import putime.newspaperagent.supplier.Supplier;

/**
 *
 * @author Khai
 */
public class frmLine extends javax.swing.JFrame {

    Vector<Line> vLine;
    ModelLine modelLine;

    /**
     * Creates new form frmLine
     */
    public frmLine() {
        initComponents();
        initCoboxList();
    }

    public void initCoboxList() {
        modelLine = new ModelLine();
        vLine = new Vector<>();
        vLine = modelLine.initComboxLine();
        DefaultListModel dlm = new DefaultListModel();
        for (Line line : vLine) {
            dlm.addElement(line + "                  " + line.getName());
        }
        lstLine.setModel(dlm);

        DefaultComboBoxModel dcm = new DefaultComboBoxModel(vLine);
        cobLine.setModel(dcm);
        CobChange();


    }

    public void CobChange() {
        try {
            int chon = Integer.parseInt(String.valueOf(cobLine.getSelectedItem()));
            Line line = modelLine.ComboChange(chon);
            txtLineID.setText(String.valueOf(line.getLineID()));
            txtName.setText(line.getName());
            txaAddress.setText(line.getAddress());
            txtTelephone.setText(line.getTel());
            txtDate.setDate(line.getHireDate());

            vLine = modelLine.initComboxLine();
        } catch (NumberFormatException e) {
            txtLineID.setText("");
            txtName.setText("");
            txaAddress.setText("");
            txtTelephone.setText("");
            txtDate.setDate(null);
        }
    }

    public boolean CheckValidate() {
        Pattern patter = Pattern.compile("^[a-zA-Z][a-zA-Z\\s]*");
        Matcher matcher = patter.matcher(txtName.getText());
        if (!matcher.matches()) {
            JOptionPane.showMessageDialog(this, "Wrong Name!, Please iput again!");
            return false;
        }

        if (txaAddress.getText().trim().length() == 0) {
            JOptionPane.showMessageDialog(this, "Address must > 0 character");
            return false;
        }
        patter = Pattern.compile("\\d{5,15}");
        matcher = patter.matcher(txtTelephone.getText().trim());
        if (!matcher.matches()) {
            JOptionPane.showMessageDialog(this, "Wrong Telephone!, Please iput again!");
            return false;
        }
        return true;

    }

    /**
     * This method is called from within the constructor to initialize the form.
     * WARNING: Do NOT modify this code. The content of this method is always
     * regenerated by the Form Editor.
     */
    @SuppressWarnings("unchecked")
    // <editor-fold defaultstate="collapsed" desc="Generated Code">//GEN-BEGIN:initComponents
    private void initComponents() {

        btnCancel = new javax.swing.JButton();
        btnFind = new javax.swing.JButton();
        btnEdit = new javax.swing.JButton();
        btnDelete = new javax.swing.JButton();
        jPanel2 = new javax.swing.JPanel();
        jLabel2 = new javax.swing.JLabel();
        jLabel3 = new javax.swing.JLabel();
        jLabel4 = new javax.swing.JLabel();
        jLabel5 = new javax.swing.JLabel();
        txtLineID = new javax.swing.JTextField();
        txtName = new javax.swing.JTextField();
        txtTelephone = new javax.swing.JTextField();
        jScrollPane2 = new javax.swing.JScrollPane();
        txaAddress = new javax.swing.JTextArea();
        txtDate = new com.toedter.calendar.JDateChooser();
        jLabel6 = new javax.swing.JLabel();
        jpanelSupplier = new javax.swing.JPanel();
        jLabel1 = new javax.swing.JLabel();
        cobLine = new javax.swing.JComboBox();
        jScrollPane1 = new javax.swing.JScrollPane();
        lstLine = new javax.swing.JList();
        btnNew = new javax.swing.JButton();

        setDefaultCloseOperation(javax.swing.WindowConstants.EXIT_ON_CLOSE);

        btnCancel.setText("Cancel");
        btnCancel.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                btnCancelActionPerformed(evt);
            }
        });

        btnFind.setText("Find");
        btnFind.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                btnFindActionPerformed(evt);
            }
        });

        btnEdit.setText("Edit");
        btnEdit.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                btnEditActionPerformed(evt);
            }
        });

        btnDelete.setText("Delete");
        btnDelete.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                btnDeleteActionPerformed(evt);
            }
        });

        jPanel2.setBorder(javax.swing.BorderFactory.createTitledBorder(null, "Details", javax.swing.border.TitledBorder.DEFAULT_JUSTIFICATION, javax.swing.border.TitledBorder.DEFAULT_POSITION, null, new java.awt.Color(51, 102, 255)));

        jLabel2.setText("Supplier ID");

        jLabel3.setText("Name");

        jLabel4.setText("Address");

        jLabel5.setText("Hire Date");

        txtLineID.setEditable(false);

        txaAddress.setColumns(20);
        txaAddress.setRows(5);
        jScrollPane2.setViewportView(txaAddress);

        jLabel6.setText("Telephone No");

        javax.swing.GroupLayout jPanel2Layout = new javax.swing.GroupLayout(jPanel2);
        jPanel2.setLayout(jPanel2Layout);
        jPanel2Layout.setHorizontalGroup(
            jPanel2Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(jPanel2Layout.createSequentialGroup()
                .addContainerGap()
                .addGroup(jPanel2Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.TRAILING, false)
                    .addGroup(jPanel2Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                        .addGroup(jPanel2Layout.createSequentialGroup()
                            .addComponent(jLabel2)
                            .addGap(31, 31, 31)
                            .addComponent(txtLineID, javax.swing.GroupLayout.PREFERRED_SIZE, 86, javax.swing.GroupLayout.PREFERRED_SIZE))
                        .addGroup(jPanel2Layout.createSequentialGroup()
                            .addGroup(jPanel2Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                                .addComponent(jLabel3)
                                .addComponent(jLabel4))
                            .addGap(44, 44, 44)
                            .addGroup(jPanel2Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                                .addComponent(txtName, javax.swing.GroupLayout.PREFERRED_SIZE, 235, javax.swing.GroupLayout.PREFERRED_SIZE)
                                .addComponent(jScrollPane2, javax.swing.GroupLayout.PREFERRED_SIZE, 246, javax.swing.GroupLayout.PREFERRED_SIZE))))
                    .addGroup(jPanel2Layout.createSequentialGroup()
                        .addGroup(jPanel2Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                            .addComponent(jLabel6)
                            .addComponent(jLabel5))
                        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
                        .addGroup(jPanel2Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                            .addComponent(txtTelephone, javax.swing.GroupLayout.PREFERRED_SIZE, 217, javax.swing.GroupLayout.PREFERRED_SIZE)
                            .addComponent(txtDate, javax.swing.GroupLayout.PREFERRED_SIZE, 186, javax.swing.GroupLayout.PREFERRED_SIZE))
                        .addGap(27, 27, 27)))
                .addContainerGap(34, Short.MAX_VALUE))
        );
        jPanel2Layout.setVerticalGroup(
            jPanel2Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(jPanel2Layout.createSequentialGroup()
                .addGap(20, 20, 20)
                .addGroup(jPanel2Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                    .addComponent(jLabel2)
                    .addComponent(txtLineID, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
                .addGap(18, 18, 18)
                .addGroup(jPanel2Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                    .addComponent(jLabel3)
                    .addComponent(txtName, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
                .addGap(30, 30, 30)
                .addGroup(jPanel2Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                    .addComponent(jLabel4)
                    .addComponent(jScrollPane2, javax.swing.GroupLayout.PREFERRED_SIZE, 87, javax.swing.GroupLayout.PREFERRED_SIZE))
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED, 27, Short.MAX_VALUE)
                .addGroup(jPanel2Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                    .addComponent(txtTelephone, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                    .addComponent(jLabel6))
                .addGap(34, 34, 34)
                .addGroup(jPanel2Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                    .addComponent(txtDate, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                    .addComponent(jLabel5))
                .addGap(30, 30, 30))
        );

        jpanelSupplier.setBorder(javax.swing.BorderFactory.createTitledBorder(null, "Supplier Master", javax.swing.border.TitledBorder.DEFAULT_JUSTIFICATION, javax.swing.border.TitledBorder.DEFAULT_POSITION, null, new java.awt.Color(51, 102, 255)));

        jLabel1.setText("Supplier ID");

        cobLine.setModel(new javax.swing.DefaultComboBoxModel(new String[] { "Item 1", "Item 2", "Item 3", "Item 4" }));
        cobLine.addItemListener(new java.awt.event.ItemListener() {
            public void itemStateChanged(java.awt.event.ItemEvent evt) {
                cobLineItemStateChanged(evt);
            }
        });

        lstLine.setModel(new javax.swing.AbstractListModel() {
            String[] strings = { "Item 1", "Item 2", "Item 3", "Item 4", "Item 5" };
            public int getSize() { return strings.length; }
            public Object getElementAt(int i) { return strings[i]; }
        });
        lstLine.setSelectionMode(javax.swing.ListSelectionModel.SINGLE_SELECTION);
        lstLine.addListSelectionListener(new javax.swing.event.ListSelectionListener() {
            public void valueChanged(javax.swing.event.ListSelectionEvent evt) {
                lstLineValueChanged(evt);
            }
        });
        jScrollPane1.setViewportView(lstLine);

        javax.swing.GroupLayout jpanelSupplierLayout = new javax.swing.GroupLayout(jpanelSupplier);
        jpanelSupplier.setLayout(jpanelSupplierLayout);
        jpanelSupplierLayout.setHorizontalGroup(
            jpanelSupplierLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(jpanelSupplierLayout.createSequentialGroup()
                .addGroup(jpanelSupplierLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                    .addGroup(jpanelSupplierLayout.createSequentialGroup()
                        .addComponent(jLabel1)
                        .addGap(18, 18, 18)
                        .addComponent(cobLine, 0, 131, Short.MAX_VALUE))
                    .addComponent(jScrollPane1))
                .addContainerGap())
        );
        jpanelSupplierLayout.setVerticalGroup(
            jpanelSupplierLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(jpanelSupplierLayout.createSequentialGroup()
                .addContainerGap()
                .addGroup(jpanelSupplierLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                    .addComponent(jLabel1)
                    .addComponent(cobLine, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
                .addGap(18, 18, 18)
                .addComponent(jScrollPane1, javax.swing.GroupLayout.DEFAULT_SIZE, 287, Short.MAX_VALUE))
        );

        btnNew.setText("New");
        btnNew.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                btnNewActionPerformed(evt);
            }
        });

        javax.swing.GroupLayout layout = new javax.swing.GroupLayout(getContentPane());
        getContentPane().setLayout(layout);
        layout.setHorizontalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(layout.createSequentialGroup()
                .addGap(39, 39, 39)
                .addComponent(jpanelSupplier, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                .addGap(18, 18, 18)
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                    .addGroup(layout.createSequentialGroup()
                        .addComponent(btnFind)
                        .addGap(14, 14, 14)
                        .addComponent(btnNew)
                        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
                        .addComponent(btnEdit)
                        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
                        .addComponent(btnDelete)
                        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                        .addComponent(btnCancel))
                    .addComponent(jPanel2, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
                .addContainerGap(51, Short.MAX_VALUE))
        );
        layout.setVerticalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(layout.createSequentialGroup()
                .addGap(21, 21, 21)
                .addComponent(jpanelSupplier, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                .addGap(18, 18, Short.MAX_VALUE))
            .addGroup(javax.swing.GroupLayout.Alignment.TRAILING, layout.createSequentialGroup()
                .addContainerGap(21, Short.MAX_VALUE)
                .addComponent(jPanel2, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                .addGap(18, 18, 18)
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                    .addComponent(btnFind)
                    .addComponent(btnCancel)
                    .addComponent(btnDelete)
                    .addComponent(btnEdit)
                    .addComponent(btnNew))
                .addGap(38, 38, 38))
        );

        pack();
    }// </editor-fold>//GEN-END:initComponents

    private void btnCancelActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_btnCancelActionPerformed
        this.dispose();
    }//GEN-LAST:event_btnCancelActionPerformed

    private void btnFindActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_btnFindActionPerformed
        new FindLine(this, true).setVisible(true);
    }//GEN-LAST:event_btnFindActionPerformed
    boolean status = true;
    private void btnEditActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_btnEditActionPerformed
        if (status) {
            btnFind.setEnabled(false);
            btnNew.setEnabled(false);
            btnDelete.setEnabled(false);
            txtName.setBackground(Color.yellow);
            txaAddress.setBackground(Color.yellow);
            txtTelephone.setBackground(Color.yellow);
            txtDate.setBackground(Color.yellow);
            btnEdit.setText("Update");
            status = false;
        } else {
            if (!CheckValidate()) {
                return;
            }
            int chon = Integer.parseInt(txtLineID.getText());
            String name = txtName.getText();
            String address = txaAddress.getText();
            String tel = txtTelephone.getText();
            SimpleDateFormat sdf = new SimpleDateFormat();
            Date date;
            try {
                date = new Date(Date.parse(sdf.format(txtDate.getDate())));
            } catch (NullPointerException e) {
                JOptionPane.showMessageDialog(this, "You must input the correct Hire Date formats: MMM d, yyyy ");
                return;
            }

            if (modelLine.editLine(chon, name, address, tel, date)) {
                JOptionPane.showMessageDialog(this, "Update Successfully !");

                vLine = new Vector<>();
                vLine = modelLine.initComboxLine();
                DefaultListModel dlm = new DefaultListModel();
                for (Line line : vLine) {
                    dlm.addElement(line + "                  " + line.getName());
                }
                lstLine.setModel(dlm);

            } else {
                JOptionPane.showMessageDialog(this, "Fail !");
            }

            btnFind.setEnabled(true);
            btnNew.setEnabled(true);
            btnDelete.setEnabled(true);
            txtName.setBackground(Color.white);
            txaAddress.setBackground(Color.white);
            txtTelephone.setBackground(Color.white);
            txtDate.setBackground(Color.white);
            btnEdit.setText("Edit");
            status = true;
        }
    }

    public void findLine(int chon) {
        ComboBoxModel model = cobLine.getModel();
        model.setSelectedItem(chon);
    }//GEN-LAST:event_btnEditActionPerformed

    private void btnDeleteActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_btnDeleteActionPerformed
        int tam = JOptionPane.showConfirmDialog(this, "You want delete Line Id: " + String.valueOf(cobLine.getSelectedItem()));
        if (tam == 0) {
            int chon = Integer.parseInt(String.valueOf(cobLine.getSelectedItem()));
            System.out.println(chon);
            if (modelLine.deleteLine(chon)) {
                JOptionPane.showMessageDialog(this, "Delete Successfully!");
                initCoboxList();
            } else {
                JOptionPane.showMessageDialog(this, "Fail!!");
            }
        }
    }//GEN-LAST:event_btnDeleteActionPerformed

    private void cobLineItemStateChanged(java.awt.event.ItemEvent evt) {//GEN-FIRST:event_cobLineItemStateChanged
        if (evt.getStateChange() == ItemEvent.SELECTED) {
            CobChange();
        }
    }//GEN-LAST:event_cobLineItemStateChanged

    private void lstLineValueChanged(javax.swing.event.ListSelectionEvent evt) {//GEN-FIRST:event_lstLineValueChanged
        if (evt.getValueIsAdjusting()) {
            cobLine.setSelectedIndex(lstLine.getSelectedIndex());
        }
    }//GEN-LAST:event_lstLineValueChanged

    private void btnNewActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_btnNewActionPerformed
        new AddLine(this, true).setVisible(true);
    }//GEN-LAST:event_btnNewActionPerformed

    /**
     * @param args the command line arguments
     */
    public static void main(String args[]) {
        /* Set the Nimbus look and feel */
        //<editor-fold defaultstate="collapsed" desc=" Look and feel setting code (optional) ">
        /* If Nimbus (introduced in Java SE 6) is not available, stay with the default look and feel.
         * For details see http://download.oracle.com/javase/tutorial/uiswing/lookandfeel/plaf.html 
         */
        try {
            for (javax.swing.UIManager.LookAndFeelInfo info : javax.swing.UIManager.getInstalledLookAndFeels()) {
                if ("Nimbus".equals(info.getName())) {
                    javax.swing.UIManager.setLookAndFeel(info.getClassName());
                    break;
                }
            }
        } catch (ClassNotFoundException ex) {
            java.util.logging.Logger.getLogger(frmLine.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
        } catch (InstantiationException ex) {
            java.util.logging.Logger.getLogger(frmLine.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
        } catch (IllegalAccessException ex) {
            java.util.logging.Logger.getLogger(frmLine.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
        } catch (javax.swing.UnsupportedLookAndFeelException ex) {
            java.util.logging.Logger.getLogger(frmLine.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
        }
        //</editor-fold>

        /* Create and display the form */
        java.awt.EventQueue.invokeLater(new Runnable() {
            public void run() {
                new frmLine().setVisible(true);
            }
        });
    }
    // Variables declaration - do not modify//GEN-BEGIN:variables
    private javax.swing.JButton btnCancel;
    private javax.swing.JButton btnDelete;
    private javax.swing.JButton btnEdit;
    private javax.swing.JButton btnFind;
    private javax.swing.JButton btnNew;
    private javax.swing.JComboBox cobLine;
    private javax.swing.JLabel jLabel1;
    private javax.swing.JLabel jLabel2;
    private javax.swing.JLabel jLabel3;
    private javax.swing.JLabel jLabel4;
    private javax.swing.JLabel jLabel5;
    private javax.swing.JLabel jLabel6;
    private javax.swing.JPanel jPanel2;
    private javax.swing.JScrollPane jScrollPane1;
    private javax.swing.JScrollPane jScrollPane2;
    private javax.swing.JPanel jpanelSupplier;
    private javax.swing.JList lstLine;
    private javax.swing.JTextArea txaAddress;
    private com.toedter.calendar.JDateChooser txtDate;
    private javax.swing.JTextField txtLineID;
    private javax.swing.JTextField txtName;
    private javax.swing.JTextField txtTelephone;
    // End of variables declaration//GEN-END:variables
}
